package com.can.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.can.convert.CategoryConvert;
import com.can.domain.ResponseResult;
import com.can.domain.entity.Category;
import com.can.domain.vo.ExcelCategoryVO;
import com.can.domain.vo.PageVO;
import com.can.enums.AppHttpCodeEnum;
import com.can.service.CategoryService;
import com.can.util.WebUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

import static com.can.constant.SystemConstants.STATUS_NORMAL;

@RestController
@RequestMapping("/content/category")
public class CategoryController {

    @Resource
    private CategoryService categoryService;

    @GetMapping("/list")
    public ResponseResult list(Integer pageNum, Integer pageSize, Category category) {
        Page<Category> result = new Page<>(pageNum, pageSize);
        categoryService.page(result, new LambdaQueryWrapper<Category>()
                .like(StringUtils.hasText(category.getName()), Category::getName, category.getName())
                .eq(StringUtils.hasText(category.getStatus()), Category::getStatus, category.getStatus())
        );
        return ResponseResult.okResult(new PageVO(result.getRecords(), result.getTotal()));
    }

    /**
     * 所有分类
     */
    @GetMapping("/listAllCategory")
    public ResponseResult listAllCategory() {
        return ResponseResult.okResult(
                categoryService.list(
                        new LambdaQueryWrapper<Category>().eq(Category::getStatus, STATUS_NORMAL)
                ));
    }

    /**
     * 导出分类: 因为把文件数据写到了响应体中,所以就无法再写入json数据,所以这里返回类型只能是void,不能是ResponseResult
     *
     * @param response
     */
    @PreAuthorize("@ps.hasPersmission('content:category:export')")
    @GetMapping("/export")
    public void export(HttpServletResponse response) {
        try {
            //设置下载文件的请求头
            WebUtils.setDownLoadHeader("分类.xlsx", response);
            //获取需要导出的数据
            List<Category> categoryVos = categoryService.list();

            List<ExcelCategoryVO> excelCategoryVOS = CategoryConvert.INSTANCE.convertList01(categoryVos);

            //把数据写入到Excel中
            EasyExcel.write(response.getOutputStream(), ExcelCategoryVO.class)
                    .autoCloseStream(Boolean.FALSE)
                    .sheet("分类导出")
                    .doWrite(excelCategoryVOS);

        } catch (Exception e) {
            //如果出现异常也要响应json
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
            WebUtils.renderString(response, JSON.toJSONString(result));
        }
    }

    @PostMapping
    public ResponseResult add(@RequestBody Category category) {
        // 默认没父分类
        category.setPid(-1L);
        categoryService.save(category);
        return ResponseResult.okResult();
    }

    @GetMapping("/{id}")
    public ResponseResult get(@PathVariable Long id) {
        return ResponseResult.okResult(categoryService.getById(id));
    }

    @PutMapping
    public ResponseResult get(@RequestBody Category category) {
        categoryService.updateById(category);
        return ResponseResult.okResult();
    }

    @DeleteMapping("/{id}")
    public ResponseResult del(@PathVariable Long id) {
        categoryService.removeById(id);
        return ResponseResult.okResult();
    }

}